<?php

namespace app\model;

use think\Model;

class Game extends Model
{
    // 设置当前模型对应的数据表
    protected $name = 'game';
    // 设置当前模型主键
    protected $pk = 'id';

    // 添加/修改数据
    public function edit($params)
    {
        if (empty($params['id'])) {
            $data = self::create($params);
            return $data->id;
        }
		self::update($params);
        return $params['id'];
    }

    // 根据id获取数据
    public function getInfoById($id, $fields = 'id, name')
    {
        $data = $this::where(['id' => $id])->field($fields)->find();
        return $data ? $data->toArray() : [];
    }

    // 获取分页数据
    public function getPagingDataByWhere($where = [], $page = 1, $limit = 10, $fields = 'id, name', $order = 'id desc')
    {
        $total = $this::where($where)->count();

        if ($total == 0) {
            return ['total' => 0, 'total_page' => 0, 'data' => []];
        }

        $totalPage = ceil($total / $limit);
        $offset = ($page - 1) * $limit;

        $data = $this::where($where)->field($fields)->order($order)->limit($offset, $limit)->select()->toArray();

        return ['total' => $total, 'total_page' => $totalPage, 'data' => $data];
    }

    // 获取所有数据
    public function getDataByWhere($where = [], $fields = 'id, name', $order = 'id desc')
    {
        $data = $this::where($where)->field($fields)->order($order)->select();
        return $data ? $data->toArray() : [];
    }

    // 根据条件获取一条数据
    public function getInfoByWhere(array $where, $fields = 'id, name')
    {
        $data = $this::where($where)->field($fields)->find();
        return $data ? $data->toArray() : [];
    }
}